package org.jeecg.modules.mes.inspect.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.mes.client.CertificateClient;
import org.jeecg.modules.mes.client.OrderClient;
import org.jeecg.modules.mes.inspect.entity.MaterielRetreatReason;
import org.jeecg.modules.mes.inspect.entity.MaterielRetreatRecord;
import org.jeecg.modules.mes.inspect.service.IMaterielRetreatReasonService;
import org.jeecg.modules.mes.inspect.service.IMaterielRetreatRecordService;
import org.jeecg.modules.mes.order.entity.MesOrderPurchase;
import org.jeecg.modules.mes.order.entity.MesPurchaseItem;
import org.jeecg.modules.mes.storage.entity.MesCertificateItem;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

 /**
 * @Description: 物料退料记录表
 * @Author: jeecg-boot
 * @Date:   2021-04-25
 * @Version: V1.0
 */
@Api(tags="物料退料记录表")
@RestController
@RequestMapping("/inspect/materielRetreatRecord")
@Slf4j
public class MaterielRetreatRecordController extends JeecgController<MaterielRetreatRecord, IMaterielRetreatRecordService> {

	@Autowired
	private IMaterielRetreatRecordService materielRetreatRecordService;

	@Autowired
	private IMaterielRetreatReasonService materielRetreatReasonService;

	@Autowired
	private OrderClient orderClient;
	@Autowired
	private CertificateClient certificateClient;
	/*---------------------------------主表处理-begin-------------------------------------*/
	/**
	 * 分页列表查询
	 * @param materielRetreatRecord
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "物料退料记录表-分页列表查询")
	@ApiOperation(value="物料退料记录表-分页列表查询", notes="物料退料记录表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(MaterielRetreatRecord materielRetreatRecord,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MaterielRetreatRecord> queryWrapper = QueryGenerator.initQueryWrapper(materielRetreatRecord, req.getParameterMap());
		Page<MaterielRetreatRecord> page = new Page<MaterielRetreatRecord>(pageNo, pageSize);
		IPage<MaterielRetreatRecord> pageList = materielRetreatRecordService.page(page, queryWrapper);
		for (int j = 0; j < pageList.getRecords().size(); j++) {
			List<MaterielRetreatReason> materielRetreatReasons = materielRetreatReasonService.selectByMainId(pageList.getRecords().get(j).getId());
			for (int i = 0; i < materielRetreatReasons.size() ; i++) {
				if("破损".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason1(materielRetreatReasons.get(i).getNumber());
				}
				if("断裂".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason2(materielRetreatReasons.get(i).getNumber());
				}
				if("划伤".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason3(materielRetreatReasons.get(i).getNumber());
				}
				if("来料损件".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason4(materielRetreatReasons.get(i).getNumber());
				}
				if("尺寸不符".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason5(materielRetreatReasons.get(i).getNumber());
				}
				if("功能不良".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason6(materielRetreatReasons.get(i).getNumber());
				}
				if("实物与焊盘不符".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason7(materielRetreatReasons.get(i).getNumber());
				}
				if("料号不符".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason8(materielRetreatReasons.get(i).getNumber());
				}
				if("线束不良".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason9(materielRetreatReasons.get(i).getNumber());
				}
				if("型号不符".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason10(materielRetreatReasons.get(i).getNumber());
				}
				if("其他".equals( materielRetreatReasons.get(i).getReason())) {
					pageList.getRecords().get(j).setReason11(materielRetreatReasons.get(i).getNumber());
				}
			}
		}

		return Result.ok(pageList);
	}

	/**
     *   添加
     * @param materielRetreatRecord
     * @return
     */
    @AutoLog(value = "物料退料记录表-添加")
    @ApiOperation(value="物料退料记录表-添加", notes="物料退料记录表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody MaterielRetreatRecord materielRetreatRecord) {
        materielRetreatRecordService.saveAll(materielRetreatRecord);
        return Result.ok("添加成功！");
    }

	 /**
	  *   app添加
	  * @param materielRetreatRecord
	  * @return
	  */
	 @AutoLog(value = "物料退料记录表-app添加")
	 @ApiOperation(value="物料退料记录表-app添加", notes="物料退料记录表-app添加")
	 @PostMapping(value = "/appadd")
	 public Result<?> appadd(@RequestBody MaterielRetreatRecord materielRetreatRecord) {
	 	//根据凭证抬头id去获取采购订单编号
		if(StringUtils.isBlank(materielRetreatRecord.getReserveCode())){
			Result.error("凭证项目预留编号不能为空！");
		}
		MesOrderPurchase purchaseinfo = orderClient.getPurchaseNameById(materielRetreatRecord.getReserveCode());
		materielRetreatRecord.setOrderCode(purchaseinfo.getOrderCode());
//		 MesPurchaseItem mesPurchaseItem = orderClient.queryMesPurchaseItemListById(materielRetreatRecord.getReserveCode());
//		 materielRetreatRecord.setUnit(mesPurchaseItem.getOrderUnit());
//		 materielRetreatRecord.setMaterielSpecs(mesPurchaseItem.getMaterielGauge());
//		 materielRetreatRecord.setMaterielCode(mesPurchaseItem.getMaterielCode());
		 materielRetreatRecordService.saveAll(materielRetreatRecord);

		 //加未收货数量，
		 String retreatNum = materielRetreatRecord.getRetreatNum();
		 MesPurchaseItem mesPurchaseItem = orderClient.queryMesPurchaseItemListById(materielRetreatRecord.getReserveCode());
		 BigDecimal retreatNum2 = new BigDecimal(retreatNum);
		 BigDecimal unreceiveNum = new BigDecimal(mesPurchaseItem.getUnreceiveNum());
		 BigDecimal retreatNum3=unreceiveNum.add(retreatNum2);//新的未收货数量=未收货数量+退料数量
		 mesPurchaseItem.setUnreceiveNum(retreatNum3.toString());
		 orderClient.editPurchaseItem(mesPurchaseItem);

		 //减未录入数量和未入库数量
		 MesCertificateItem item = certificateClient.queryCertificateItemById(materielRetreatRecord.getPerkItemId());

		 BigDecimal inputNum = new BigDecimal("0");
		 if (StringUtils.isNotBlank(item.getInputNum())){
			 inputNum=new BigDecimal(item.getInputNum());
		 }
		 BigDecimal subtract = inputNum.subtract(retreatNum2);
		 item.setInputNum(subtract.toString());
		 BigDecimal unstorageNum = new BigDecimal("0");
		 if (StringUtils.isNotBlank(item.getUnstorageNum())){
			 unstorageNum=new BigDecimal(item.getUnstorageNum());
		 }
		 BigDecimal subtract2 = unstorageNum.subtract(retreatNum2);
		 item.setUnstorageNum(subtract2.toString());
		 certificateClient.editCertificateItem(item);
		 return Result.ok("添加成功！");
	 }

    /**
     *  编辑
     * @param materielRetreatRecord
     * @return
     */
    @AutoLog(value = "物料退料记录表-编辑")
    @ApiOperation(value="物料退料记录表-编辑", notes="物料退料记录表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody MaterielRetreatRecord materielRetreatRecord) {
        materielRetreatRecordService.updateByedit(materielRetreatRecord);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     * @param id
     * @return
     */
    @AutoLog(value = "物料退料记录表-通过id删除")
    @ApiOperation(value="物料退料记录表-通过id删除", notes="物料退料记录表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name="id",required=true) String id) {
        materielRetreatRecordService.delMain(id);
        return Result.ok("删除成功!");
    }

	 /**
	  * 通过id删除
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "物料退料记录表-通过id删除")
	 @ApiOperation(value="物料退料记录表-通过id删除", notes="物料退料记录表-通过id删除")
	 @GetMapping(value = "/queryById")
	 public MaterielRetreatRecord queryById(@RequestParam(name="id",required=true) String id) {
		 MaterielRetreatRecord byId = materielRetreatRecordService.getById(id);
		 List<MaterielRetreatReason> materielRetreatReasons = materielRetreatReasonService.selectByMainId(id);
		 for (int i = 0; i < materielRetreatReasons.size() ; i++) {
			if("破损".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason1(materielRetreatReasons.get(i).getNumber());
			}
			if("断裂".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason2(materielRetreatReasons.get(i).getNumber());
			}
			if("划伤".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason3(materielRetreatReasons.get(i).getNumber());
			}
			if("来料损件".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason4(materielRetreatReasons.get(i).getNumber());
			}
			if("尺寸不符".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason5(materielRetreatReasons.get(i).getNumber());
			}
			if("功能不良".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason6(materielRetreatReasons.get(i).getNumber());
			}
			if("实物与焊盘不符".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason7(materielRetreatReasons.get(i).getNumber());
			}
			if("料号不符".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason8(materielRetreatReasons.get(i).getNumber());
			}
			if("线束不良".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason9(materielRetreatReasons.get(i).getNumber());
			}
			if("型号不符".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason10(materielRetreatReasons.get(i).getNumber());
			}
			if("其他".equals( materielRetreatReasons.get(i).getReason())) {
				byId.setReason11(materielRetreatReasons.get(i).getNumber());
			}
		 }
		 return byId;
	 }


	 /**
     * 批量删除
     * @param ids
     * @return
     */
    @AutoLog(value = "物料退料记录表-批量删除")
    @ApiOperation(value="物料退料记录表-批量删除", notes="物料退料记录表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
        this.materielRetreatRecordService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, MaterielRetreatRecord materielRetreatRecord) {
        return super.exportXls(request, materielRetreatRecord, MaterielRetreatRecord.class, "物料退料记录表");
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MaterielRetreatRecord.class);
    }
	/*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-退料原因表-begin----------------------------------------------*/
	/**
	 * 通过主表ID查询
	 * @return
	 */
	@AutoLog(value = "退料原因表-通过主表ID查询")
	@ApiOperation(value="退料原因表-通过主表ID查询", notes="退料原因表-通过主表ID查询")
	@GetMapping(value = "/listMaterielRetreatReasonByMainId")
    public Result<?> listMaterielRetreatReasonByMainId(MaterielRetreatReason materielRetreatReason,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<MaterielRetreatReason> queryWrapper = QueryGenerator.initQueryWrapper(materielRetreatReason, req.getParameterMap());
        Page<MaterielRetreatReason> page = new Page<MaterielRetreatReason>(pageNo, pageSize);
        IPage<MaterielRetreatReason> pageList = materielRetreatReasonService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

	/**
	 * 添加
	 * @param materielRetreatReason
	 * @return
	 */
	@AutoLog(value = "退料原因表-添加")
	@ApiOperation(value="退料原因表-添加", notes="退料原因表-添加")
	@PostMapping(value = "/addMaterielRetreatReason")
	public Result<?> addMaterielRetreatReason(@RequestBody MaterielRetreatReason materielRetreatReason) {
		materielRetreatReasonService.save(materielRetreatReason);
		return Result.ok("添加成功！");
	}

    /**
	 * 编辑
	 * @param materielRetreatReason
	 * @return
	 */
	@AutoLog(value = "退料原因表-编辑")
	@ApiOperation(value="退料原因表-编辑", notes="退料原因表-编辑")
	@PutMapping(value = "/editMaterielRetreatReason")
	public Result<?> editMaterielRetreatReason(@RequestBody MaterielRetreatReason materielRetreatReason) {
		materielRetreatReasonService.updateById(materielRetreatReason);
		return Result.ok("编辑成功!");
	}

	/**
	 * 通过id删除
	 * @param id
	 * @return
	 */
	@AutoLog(value = "退料原因表-通过id删除")
	@ApiOperation(value="退料原因表-通过id删除", notes="退料原因表-通过id删除")
	@DeleteMapping(value = "/deleteMaterielRetreatReason")
	public Result<?> deleteMaterielRetreatReason(@RequestParam(name="id",required=true) String id) {
		materielRetreatReasonService.removeById(id);
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "退料原因表-批量删除")
	@ApiOperation(value="退料原因表-批量删除", notes="退料原因表-批量删除")
	@DeleteMapping(value = "/deleteBatchMaterielRetreatReason")
	public Result<?> deleteBatchMaterielRetreatReason(@RequestParam(name="ids",required=true) String ids) {
	    this.materielRetreatReasonService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}

    /**
     * 导出
     * @return
     */
    @RequestMapping(value = "/exportMaterielRetreatReason")
    public ModelAndView exportMaterielRetreatReason(HttpServletRequest request, MaterielRetreatReason materielRetreatReason) {
		 // Step.1 组装查询条件
		 QueryWrapper<MaterielRetreatReason> queryWrapper = QueryGenerator.initQueryWrapper(materielRetreatReason, request.getParameterMap());
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		 // Step.2 获取导出数据
		 List<MaterielRetreatReason> pageList = materielRetreatReasonService.list(queryWrapper);
		 List<MaterielRetreatReason> exportList = null;

		 // 过滤选中数据
		 String selections = request.getParameter("selections");
		 if (oConvertUtils.isNotEmpty(selections)) {
			 List<String> selectionList = Arrays.asList(selections.split(","));
			 exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		 } else {
			 exportList = pageList;
		 }

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, "退料原因表"); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, MaterielRetreatReason.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("退料原因表报表", "导出人:" + sysUser.getRealname(), "退料原因表"));
		 mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		 return mv;
    }

    /**
     * 导入
     * @return
     */
    @RequestMapping(value = "/importMaterielRetreatReason/{mainId}")
    public Result<?> importMaterielRetreatReason(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<MaterielRetreatReason> list = ExcelImportUtil.importExcel(file.getInputStream(), MaterielRetreatReason.class, params);
				 for (MaterielRetreatReason temp : list) {
                    temp.setMainId(mainId);
				 }
				 long start = System.currentTimeMillis();
				 materielRetreatReasonService.saveBatch(list);
				 log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
    }

    /*--------------------------------子表处理-退料原因表-end----------------------------------------------*/




}
